package tests;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.rmi.RemoteException;
import java.rmi.registry.Registry;
import java.util.Date;
import java.util.Random;

import pa2.*;

public class TestCase3 {
	String host = "localhost";
	String port = Integer.toString(Registry.REGISTRY_PORT);
	IMyKVPeer[] peers = null;

	String file = "testCase.csv";
	FileWriter fwriter = null;

	private long startTime = 0;
	private long endTime = 0;
	private long time = 0;

	public TestCase3(IMyKVPeer[] peers) {
		this.peers = peers;
	}

	public void startTest() {

		insertTestKeys();

		File docu = new File(file);
		try {
			fwriter = new FileWriter(docu, true);
			fwriter.write("\n(TestCase3)  Size of storage for each peer: \n");

			int size = 0;
			for (int i = 0; i < IMyKVPeer.NUM_OF_PEERS; i++) {
				size = peers[i].getStorageSize();
				fwriter.append("(TestCase3) Peer" + i + ":;" + size + "\n");
				System.out.println("(TestCase3) Peer" + i + " has " + size + " entries.");
			}

			fwriter.flush();
			fwriter.close();
		} catch (IOException e) {
			System.out
					.println("Upps... Error at writing into \"testCases.csv\"!");
			e.printStackTrace();
		}
	}
	
	/**
	 * Inserts 999 random keys 
	 */
	private void insertTestKeys(){
		Random r = new Random();
		for (int i = 0; i < 999; i++) {
			// inserting a random key when the data structure is empty
			long key = r.nextInt((int) IMyKVPeer.MAX_KEY_VALUE);
			MyKVMessage msg = new MyKVMessage(key, Long.toHexString(key));
			try {
				this.startTime = new Date().getTime();
				long insertString = peers[(int) key % IMyKVPeer.NUM_OF_PEERS].insert(msg);
				this.endTime = new Date().getTime();
				time = this.endTime - this.startTime;

//				System.out.println("(TestCase3) " + (i+1) + ". key inserted '" + msg.getKey() + "': "
//						+ " at peer " + insertString + " in " + time + " ms\n");

			} catch (RemoteException e) {
				System.out.println("Hoppala, we got a RemoteException...");
				e.printStackTrace();
			}
		}

	}
}
